package com.time.company.base;

import android.annotation.TargetApi;
import android.app.NotificationManager;
import android.content.Context;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.time.company.R;
import com.time.company.app.MyApplication;
import com.time.company.app.MyManager;
import com.time.company.common.receiver.NetReceiver;
import com.time.company.components.navigation.impl.DefaultNavigation;
import com.time.company.db.ViewModelCreator;
import com.time.company.servermodel.BasicBean;
import com.time.company.utils.ToastUtils;
import com.time.company.viewmodel.UserViewModel;
import com.time.company.webserver.listener.ResponseCallback;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.sofia.Sofia;

/**
 * Activity 基类
 * Created by Bing on 2016/8/23.
 * E-mail is tx16bing@163.com
 */
public abstract class BaseActivity extends AppCompatActivity
        implements ResponseCallback<BasicBean> {

    public MyApplication application;
    public Resources resources;
    public ViewModelCreator mVMcreator;
    public UserViewModel userViewModel;

    private static Handler handler;
    private boolean destroyed = false;
    private LocalBroadcastManager lbm;
    private NetReceiver netReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = MyApplication.getInstance();
        resources = getResources();
        mVMcreator = ViewModelCreator.getInstance(application);
        userViewModel = mVMcreator.getUserViewModel();
        // 把当前的Activity加入管理器
        MyManager.getInstance().addActivity(this);
        MobclickAgent.openActivityDurationTrack(false);//禁止默认的页面统计方式，这样将不会再自动统计Activity

        registerNetReceiver();
    }

    private void cancelAllNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancelAll();
    }

    public boolean needTranslucentStatus() {
        return false;
    }

    /**
     * 注册监听网络变化的接收器
     */
    private void registerNetReceiver() {
        lbm = LocalBroadcastManager.getInstance(this);
        netReceiver = new NetReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(netReceiver, filter);
    }

    public void setContentView(int layoutId){
        super.setContentView(layoutId);

        if (!needTranslucentStatus()){
            Sofia.with(this)
                    .statusBarBackground(ContextCompat.getColor(this, R.color.colorStatusBar))
                    .navigationBarBackground(ContextCompat.getColor(this, android.R.color.black));
        }
    }

    public void setContentView(int layoutId, int titleRes) {
         setContentView(layoutId, getString(titleRes));
    }

    public void setContentView(int layoutId, String title) {
        View rootView = LayoutInflater.from(getApplicationContext()).inflate(layoutId, null);
        setNavigation(rootView, title);
        super.setContentView(rootView);
        if (!needTranslucentStatus()){
            Sofia.with(this)
                    .statusBarBackground(ContextCompat.getColor(this, R.color.colorStatusBar))
                    .navigationBarBackground(ContextCompat.getColor(this, android.R.color.black));
        }
    }

    public void setNavigation(View view, String titleRes) {
        DefaultNavigation.Builder builder = new DefaultNavigation.Builder(getApplicationContext(), (ViewGroup) view);
        builder.setLeftImageRes(R.drawable.selector_common_back)
                .setCenterText(titleRes)
                .setCenterTextColor(R.color.black_x)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                }).create().createAndBind();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onNavigateUpClicked();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onNavigateUpClicked() {
        onBackPressed();
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(toString());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(toString());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消指定的请求
        NoHttp.getRequestQueueInstance().cancelBySign(toString());
    }

    /**
     * 当点击外部的时候隐藏软键盘
     *
     * @param ev event
     * @return 返回值
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (this.getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            // 独占本次事件，不做任何处理
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        MyManager.getInstance().removeActivity(this);
        super.onDestroy();
        destroyed = true;
        if (lbm != null) {
            lbm.unregisterReceiver(netReceiver);
        }
    }

    public boolean isDestroyedCompatible() {
        if (Build.VERSION.SDK_INT >= 17) {
            return isDestroyedCompatible17();
        } else {
            return destroyed || super.isFinishing();
        }
    }

    @TargetApi(17)
    private boolean isDestroyedCompatible17() {
        return super.isDestroyed();
    }

    protected boolean isCompatible(int apiLevel) {
        return Build.VERSION.SDK_INT >= apiLevel;
    }

    public BaseFragment switchContent(BaseFragment fragment) {
        return switchContent(fragment, false);
    }

    protected BaseFragment switchContent(BaseFragment fragment, boolean needAddToBackStack) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(fragment.getContainerId(), fragment);
        if (needAddToBackStack) {
            fragmentTransaction.addToBackStack(null);
        }
        try {
            fragmentTransaction.commitAllowingStateLoss();
        } catch (Exception e) {

        }

        return fragment;
    }

    // 初始化控件id
    protected <T extends View> T findView(int resId) {
        return (T) (findViewById(resId));
    }

    protected final Handler getHandler() {
        if (handler == null) {
            handler = new Handler(getMainLooper());
        }
        return handler;
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {

    }

    @Override
    public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
        if (exception != null) {
            if (!TextUtils.isEmpty(exception.getMessage())) {
                ToastUtils.showShort(exception.getMessage());
            }
        }
    }

    public void showKeyboard(boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        if (isShow) {
            if (getCurrentFocus() == null) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            } else {
                imm.showSoftInput(getCurrentFocus(), 0);
            }
        } else {
            if (getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }

        }
    }

}
